package com.uuj.dome.controller;

import com.uuj.dome.entity.DomeEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;
import java.util.Locale;

/**
 * ClassName:controller
 * PACKAGE_NAME:com.uuj.dome.controller
 */
@RestController
public class IndexController {

    @Autowired
    private MessageSource messageSource;

    @GetMapping(value = "/valid")
    public String validator(@Valid DomeEntity domeEntity, BindingResult result) {
        if (result.hasErrors()) {
            StringBuffer buffer = new StringBuffer();
            // 获取错误字段集合
            List<FieldError> fieldErrors = result.getFieldErrors();
            // 获取本地语音
            Locale locale = LocaleContextHolder.getLocale();
            // 遍历错误字段获取错误信息
            fieldErrors.forEach(fieldError -> {
                // 错误信息
                String message = messageSource.getMessage(fieldError, locale);
                // 添加到错误信息集合内
                buffer.append(fieldError.getField() + "：" + message + " , ");
            });
            return buffer.toString();
        }


        return "验证通过， 名称: " + domeEntity.getName() + " 年龄: " + domeEntity.getAge() + " 邮箱: " + domeEntity.getEmail();

    }


}
